 // get element
 const loginPage = document.querySelector('#login-page')
 const loginForm = document.querySelector('#login-form')
 const messagePage = document.querySelector('#message-page')
 const messageForm = document.querySelector('#message-form')
 // 聊天记录
 const chatRecord = document.querySelector('.chat-record')
 // 在线用户列表
 const userList = document.querySelector('.user-list')


 // 连接server socket io
 let socket = io({
   'timeout': 5000,
   'connect timeout': 5000
 })

 // 更新在线用户
 socket.on('loadUsers', (users) => {
   userList.innerHTML = ''
   users.map(user => {
     const userLi = document.createElement('li')
     userLi.setAttribute('class', 'collection-item center')
     userLi.innerHTML = `<h6>${user}</h6>`
     userList.insertBefore(userLi, userList.lastChild)
   })
 })

 // 登录
 loginForm.addEventListener('submit', e => {
   e.preventDefault()
   const username = document.querySelector('#name').value
   // Emit发送
   socket.emit('login', username, () => {
     // 隐藏登录页面
     loginPage.style.display = 'none'
     // 显示消息页面
     messagePage.style.display = 'block'
     // 欢迎
     const welcome = document.createElement('h6')
     welcome.textContent = `欢迎 ${username}!`
     chatRecord.insertBefore(welcome, chatRecord.lastChild)
   })
 })

 // 退出登录
 document.querySelector('.logout').addEventListener('click', () => {
   socket.emit('logout')
   loginPage.style.display = 'block'
   messagePage.style.display = 'none'
 })

 // 发送消息
 messageForm.addEventListener('submit', (e) => {
   e.preventDefault()
   const msg = document.querySelector('#messages').value
   document.querySelector('#messages').value = ''
   socket.emit('sendMessage', msg)
 })

 // 添加消息记录
 socket.on('output', data => {
   const msg = document.createElement('h6')
   msg.textContent = data.user + ": " + data.msg;
   chatRecord.insertBefore(msg, chatRecord.lastChild)
   //  超过8个就删除最先添加的一个
   if (chatRecord.querySelectorAll('h6').length > 8) {
     chatRecord.removeChild(chatRecord.firstChild)
   }
 })